import configparser
import pathlib
import base64

class account(object):
    def __init__(self, username, password, url):
        self.usn = username
        self.pwd = password
        self.url = url

    def setini(self):  # 设置ini
        conf = configparser.ConfigParser()
        path = pathlib.Path('account.ini')
        if path.exists():
            return '已存在用户信息'
        else:
            username = str(base64.b64encode(self.usn.encode('utf-8')), 'utf-8')
            password = str(base64.b64encode(self.pwd.encode('utf-8')), 'utf-8')
            url = str(base64.b64encode(self.url.encode('utf-8')), 'utf-8')
            conf['user'] = {
                'username': username,
                'password': password,
                'url': url
            }
            with open('account.ini', 'w') as file:
                conf.write(file)
                file.close()
            return '用户信息已保存'

    def cleanini(self):  # 清除ini
        path = pathlib.Path('account.ini')
        path.unlink()

    def obtainini(self):#获取ini信息
        conf = configparser.ConfigParser()
        path = pathlib.Path('account.ini')
        if path.exists():
            conf.read('account.ini')
            username_en = conf['user']['username']
            password_en = conf['user']['password']
            url_en = conf['user']['url']
            try:
                userindex_en = conf['user']['userindex']
                userindex_de = str(base64.b64decode(userindex_en))
                username_de = str(base64.b64decode(username_en))
                password_de = str(base64.b64decode(password_en))
                url_de = str(base64.b64decode(url_en))
                account = [username_de[2:-1], password_de[2:-1], url_de[2:-1],userindex_de[2:-1]]
            except:
                username_de = str(base64.b64decode(username_en))
                password_de = str(base64.b64decode(password_en))
                url_de = str(base64.b64decode(url_en))
                account = [username_de[2:-1], password_de[2:-1], url_de[2:-1]]
            return account
        else:
            return '配置信息不存在'

def modify(sections,variable,value):#修改ini
    conf = configparser.ConfigParser()
    path = pathlib.Path('account.ini')
    if path.exists():
        conf.read('account.ini')
        conf[sections][variable] = str(base64.b64encode(str(value).encode('utf-8')), 'utf-8')
        with open('account.ini', 'w') as file:
            conf.write(file)
            file.close()
        return "配置信息已修改"
    else:
        return '配置信息不存在'